const Router = require('koa-router')
const koaBody = require('koa-body')
const _ = require('lodash')
const { ECode, VCode } = require('./utils/redis')
const { codeEqual, upAvatarImg } = require('./utils')
const { error, INFO } = require('./utils/error')
const apiError = (info) => {
  error('50000', __filename, info)
}
const Passport = require('./utils/passport')
const {
  requestRegister,
  requestEditUser,
  requestEditPwd,
  requestAttention,
  requestAddAttention,
  requestFans,
  requestHistory,
  requestDynamic
} = require('./api/user')
const router = new Router({
  prefix: '/api/user'
})

router.get('/', (ctx) => {
  let result
  let code = -1
  let msg = ''
  if (ctx.isAuthenticated()) {
    code = 1
    result = ctx.session.passport.user
  } else {
    code = -1
    msg = '用户未登录'
  }
  ctx.body = {
    code,
    data: result,
    msg
  }
})
router.patch('/', async (ctx) => {
  const body = ctx.request.body ? ctx.request.body : {}
  const editUser = {
    ...body
  }
  if (body.avatar) {
    editUser.img = body.avatar
  }
  let code = -1
  let msg = ''
  try {
    const { status, data } = await requestEditUser({
      id: ctx.session.passport.user.id,
      ...editUser
    })
    if (status === 200) {
      if (data.statu === 0) {
        code = 0
        for (const item in body) {
          ctx.session.passport.user[item] = body[item]
        }
      } else {
        code = -1
        msg = data.msg
      }
    } else {
      code = -1
      msg = '系统出错'
    }
  } catch (error) {
    apiError('PATCH-/')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      msg
    }
  }
})
router.post('/', async (ctx) => {
  const body = ctx.request.body
  const ecode = await ECode.get(body.email, 'code')
  let code = -1
  let msg = ''
  try {
    if (codeEqual(ecode, body.ecode)) {
      const { status, data } = await requestRegister({
        email: body.email,
        pwd: body.pwd,
        rePwd: body.rePwd
      })
      if (status === 200 && data.statu === 0) {
        code = 0
      }
    } else {
      code = -1
      msg = '验证码不匹配'
    }
  } catch (error) {
    apiError('POST-/')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      msg
    }
  }
})
router.post('/login', async (ctx, next) => {
  const { vcode, uuid } = ctx.request.body
  const vcodeRedis = await VCode.get(uuid)
  if (!codeEqual(vcode, vcodeRedis)) {
    ctx.body = {
      code: -1,
      msg: '验证码输入错误！'
    }
    return
  }
  return Passport.authenticate('local', function(err, user, info) {
    if (err) {
      ctx.body = {
        code: -1,
        msg: err
      }
    } else if (user) {
      ctx.body = {
        code: 1,
        msg: '登录成功',
        user
      }
      return ctx.login(user)
    } else {
      ctx.body = {
        code: 1,
        msg: info
      }
    }
  })(ctx, next)
})
router.get('/logout', async (ctx) => {
  await ctx.logout()
  if (!ctx.isAuthenticated()) {
    ctx.body = {
      code: 0
    }
  } else {
    ctx.body = {
      code: -1
    }
  }
})
router.patch('/pwd', async (ctx) => {
  const { email, pwd, rePwd } = ctx.request.body
  let code = -1
  let msg = ''
  try {
    const { status, data } = await requestEditPwd({
      email,
      pwd,
      rePwd
    })
    if (status === 200) {
      if (data.statu === 0) {
        code = 0
      } else {
        msg = data.msg
      }
    } else {
      msg = '链接出错'
    }
  } catch (error) {
    apiError('PATCH-pwd')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      msg
    }
  }
})
router.get('/pwdECode', async (ctx) => {
  const body = ctx.query
  let code = -1
  let msg = ''
  const ecode = await ECode.get(body.email, 'code')
  if (codeEqual(ecode, body.ecode)) {
    code = 0
  } else {
    msg = '验证码错误'
  }
  ctx.body = {
    code,
    msg
  }
})
router.get('/dynamic', async (ctx) => {
  const { page, limit, id } = ctx.query
  let result = {}
  let code = -1
  let msg = ''
  try {
    const { status, data } = await requestDynamic({
      id,
      curr: page,
      limit
    })
    if (status === 200) {
      if (data.statu === 0) {
        code = 1
        result = data.data
          .filter((_, index) => {
            return index < limit
          })
          .map((item) => {
            return {
              id: item.id,
              title: item.title,
              imgUrl: item.img,
              classId: item.plateId,
              mapId: item.classId,
              time: item.date,
              author: {
                name: item.authorName,
                id: item.authorId,
                img: item.authorImg
              },
              browse: item.browse,
              comments: item.comments,
              content: item.content
            }
          })
      } else if (data.statu === 1) {
        code = 0
        msg = data.msg
      }
    }
  } catch (error) {
    apiError('GET-dynamic')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      data: result,
      msg
    }
  }
})
router.post(
  '/avatar',
  koaBody({
    multipart: true
  }),
  (ctx) => {
    let fileImg
    _.forIn(ctx.request.files, function(value, key) {
      fileImg = upAvatarImg(value)
    })
    ctx.body = {
      code: 1,
      data: fileImg
    }
  }
)

router.post('/attention', async (ctx) => {
  const { id, op } = ctx.request.body
  let code = -1
  let msg = ''
  try {
    const { status, data } = await requestAddAttention({
      userId: ctx.session.passport.user.id,
      id,
      op
    })
    if (status === 200) {
      if (data.statu === 0) {
        code = 0
        if (op === 1) {
          ctx.session.passport.user.follow++
        } else if (op === -1) {
          ctx.session.passport.user.follow--
        }
      } else {
        msg = data.msg
      }
    } else {
      throw new Error('50000')
    }
  } catch (error) {
    apiError('POST-attention')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      msg
    }
  }
})
router.get('/attention', async (ctx) => {
  const { page, limit, id } = ctx.query
  let result
  let code = -1
  let msg = ''
  let len = 0
  try {
    const { status, data } = await requestAttention({
      id,
      curr: page,
      limit
    })
    if (status === 200) {
      if (data.statu === 0) {
        code = 1
        len = +data.msg
        result = data.data
          .filter((_, index) => {
            return index + 1 <= limit
          })
          .map((item) => {
            return {
              id: item.id,
              name: item.name,
              attention: item.isMutual === 1,
              avatar: item.img
            }
          })
      } else {
        msg = data.msg
      }
    } else {
      throw new Error('50000')
    }
  } catch (error) {
    apiError('GET-attention')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      len,
      data: result,
      msg
    }
  }
})
router.get('/fans', async (ctx) => {
  const { page, limit, id } = ctx.query
  let result
  let code = -1
  let msg = ''
  let len = 0
  try {
    const { status, data } = await requestFans({
      id,
      curr: page,
      limit
    })
    if (status === 200 && data.statu === 0) {
      code = 1
      len = +data.msg
      result = data.data
        .filter((_, index) => {
          return index + 1 <= limit
        })
        .map((item) => {
          return {
            id: item.id,
            name: item.name,
            attention: item.isMutual === 1,
            avatar: item.img
          }
        })
    }
  } catch (error) {
    apiError('GET-fans')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      len,
      data: result,
      msg
    }
  }
})
router.get('/history', async (ctx) => {
  const { page, limit } = ctx.query
  let result
  let code = -1
  let msg = ''
  let len = 0
  try {
    const { status, data } = await requestHistory({
      id: ctx.session.passport.user.id,
      curr: page,
      limit
    })
    if (status === 200 && data.statu === 0) {
      code = 1
      len = +data.msg
      result = data.data
        .filter((_, index) => {
          return index + 1 <= limit
        })
        .map((item) => {
          return {
            id: item.id,
            title: item.title,
            time: item.date
          }
        })
    }
  } catch (error) {
    apiError('GET-history')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      len,
      data: result,
      msg
    }
  }
})
module.exports = router
